import React from "react";
import { useNavigate } from "react-router-dom";
import { createForm } from "@formily/core";
import { createSchemaField, ISchema } from "@formily/react";
import localStorage from "store2";
import api from "src/http/api";

import { Form, FormItem, Password, Submit, FormProps } from "@formily/antd";
import { Typography, notification } from "antd";
import UserInfo from ".";

const ModifyPassword: React.FC = (props) => {
  const navigate = useNavigate();
  const form = createForm();
  const SchemaField = createSchemaField({
    components: {
      FormItem,
      Password,
    },
  });

  const formProps: FormProps = {
    form,
    layout: "vertical",
    size: "large",
    style: { width: 550, padding: "24px 48px" },
    onAutoSubmit: (formData) => {
      const email = localStorage.get("userInfo")?.email;
      api.modifyPassword({ ...formData, email }).then(() => {
        navigate("/entity");
        notification.success({
          message: "Success",
          description: "修改密码成功",
          top: 65,
        });
      });
    },
  };

  const schema: ISchema = {
    type: "object",
    properties: {
      oldPassword: {
        type: "string",
        title: "原始密码",
        required: true,
        "x-decorator": "FormItem",
        "x-component": "Password",
      },
      password: {
        type: "string",
        title: "新密码",
        required: true,
        "x-decorator": "FormItem",
        "x-component": "Password",
      },
    },
  };

  return (
    <UserInfo>
      <Form {...formProps}>
        <Typography.Title level={2}>修改密码</Typography.Title>
        <SchemaField schema={schema} />
        <Submit block size="large">
          提交
        </Submit>
      </Form>
    </UserInfo>
  );
};

export default ModifyPassword;
